package org.example.backend.service.impl;

import lombok.RequiredArgsConstructor;
import org.example.backend.dto.UserPreferenceDTO;
import org.example.backend.entity.AnimalCategory;
import org.example.backend.entity.User;
import org.example.backend.entity.UserPreference;
import org.example.backend.exception.BusinessException;
import org.example.backend.repository.AnimalCategoryRepository;
import org.example.backend.repository.UserPreferenceRepository;
import org.example.backend.repository.UserRepository;
import org.example.backend.service.UserPreferenceService;
import org.example.backend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserPreferenceServiceImpl implements UserPreferenceService {

    private final UserPreferenceRepository preferenceRepository;
    private final AnimalCategoryRepository categoryRepository;
    private final UserService userService;

    @Override
    @Transactional
    public UserPreference addPreference(UserPreferenceDTO preferenceDTO) {
        User user = userService.getCurrentUser();
        AnimalCategory category = categoryRepository.findById(preferenceDTO.getCategoryId())
                .orElseThrow(() -> new BusinessException("分类不存在"));

        // 检查是否已经添加过该偏好
        if (preferenceRepository.existsByUserAndCategory(user, category)) {
            throw new BusinessException("已添加过该偏好");
        }

        UserPreference preference = new UserPreference();
        preference.setUser(user);
        preference.setCategory(category);

        return preferenceRepository.save(preference);
    }

    @Override
    @Transactional
    public void removePreference(Long categoryId) {
        User user = userService.getCurrentUser();
        AnimalCategory category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new BusinessException("分类不存在"));

        preferenceRepository.deleteByUserAndCategory(user, category);
    }

    @Override
    public List<UserPreference> getUserPreferences() {
        User user = userService.getCurrentUser();
        return preferenceRepository.findByUser(user);
    }

    @Override
    public List<UserPreference> getUserPreferences(Long userId) {
        return preferenceRepository.findByUserId(userId);
    }

    @Override
    public List<UserPreference> getCurrentUserPreferences() {
        User currentUser = userService.getCurrentUser();
        return preferenceRepository.findByUser(currentUser);
    }
} 